import datetime
import uuid
# Create your views here.
import logging
from rest_framework.views import APIView

from shareAPI2020TB import settings
from django.core.files.storage import Storage

# 20201125备注
# 这个类是重载DJANGO Storage文件存储系统内容，为了搭配ckeditor富文本编辑器，通过Setting配置CKEDITOR_STORAGE_BACKEND来实现云存储
# 具体的腾讯参数都配置到了Setting中


class StorageObject(Storage):
    def __init__(self):
        self.now = datetime.datetime.now()
        self.file = None

    def _new_name(self, name):

        #随机返回文件名称
        new_name = f"file/{str(uuid.uuid4()).replace('-', '')}.{name.split('.').pop()}"
        return new_name

    def _open(self, name, mode):
        return self.file

    def _save(self, name, content):
        """
        上传文件到腾讯服务器主代码
        """
        from qcloud_cos import CosConfig
        from qcloud_cos import CosS3Client
        from qcloud_cos import CosServiceError
        from qcloud_cos import CosClientError
        import sys
        import logging
        # 腾讯云COSV5Python SDK, 目前可以支持Python2.6与Python2.7以及Python3.x
        # pip安装指南:pip install -U cos-python-sdk-v5
        # cos最新可用地域,参照https://www.qcloud.com/document/product/436/6224

        logging.basicConfig(level=logging.INFO, stream=sys.stdout)

        # 设置用户属性, 包括secret_id, secret_key, region
        # appid已在配置中移除,请在参数Bucket中带上appid。Bucket由bucketname-appid组成
        secret_id = settings.TXUpload_SECRET_ID  # 替换为用户的secret_id
        secret_key = settings.TXUpload_SECRET_KEY  # 替换为用户的secret_key
        region = settings.TXUpload_REGION  # 替换为用户的region
        token = None  # 使用临时密钥需要传入Token，默认为空,可不填
        config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=token)  # 获取配置对象
        client = CosS3Client(config)

        # 文件上传，不局限于图片
        self.file = content
        file_data = content.file
        uploadName = self._new_name(name)
        # 字节流 简单上传
        try:
            response = client.put_object(
                Bucket=settings.TXUpload_Bucket,  # 获取腾讯存储桶名称
                Body=file_data,
                Key=uploadName,
                EnableMD5=False
            )
            return f"{settings.TXBaseUrl}/{uploadName}"
        except CosServiceError as e:
            # print(e.get_origin_msg())
            # print(e.get_digest_msg())
            print(e.get_status_code())
            print(e.get_error_code())
            # print(e.get_error_msg())
            # print(e.get_resource_location())
            # print(e.get_trace_id())
            # print(e.get_request_id())

    def exists(self, name):
        # 验证文件是否存在，因为我这边会去生成一个新的名字去存储到腾讯云，所以没有必要验证
        return False

    def url(self, name):
        # 上传完之后，已经返回的是全路径了
        return name



